import { computed, reactive, ref } from "vue";
/**
 * 后端mybatis-flex返回的标准格式数据
 */
export interface FlexPage<T = any> {
  pageNumber: number;
  pageSize: number;
  records: T[];
  totalPage: number;
  totalRow: number;
}
/**
 * 本地翻页成功后需要执行的操作
 */
type PageChangeAction<T> = (
  data: Pick<FlexPage<T>, "pageNumber" | "pageSize" | "totalRow">
) => Promise<FlexPage<T>>;

export function useFlexPageHook<T>({
  initialPageNumber = 1,
  initialPageSize = 10,
  getFlexPageData,
}: {
  initialPageNumber?: number;
  initialPageSize?: number;
  getFlexPageData: PageChangeAction<T>;
}) {
  //是否正在加载数据
  const pageLoading = ref(false);
  //是否是最后一页
  const isLastPage = computed(() => {
    return page.pageNumber >= page.totalPage && page.totalRow != -1;
  });
  //是否是第一页
  const isFirstPage = computed(() => {
    return page.pageNumber == 1;
  });
  const page: FlexPage<T> = reactive({
    pageNumber: initialPageNumber,
    pageSize: initialPageSize,
    totalPage: 0,
    totalRow: -1,
    records: [],
  });
  //加载页码数据
  async function loadPageData(pageNumber) {
    pageLoading.value = true;
    const res = await getFlexPageData({
      pageNumber: pageNumber,
      pageSize: page.pageSize,
      totalRow: page.totalRow,
    });
    page.pageNumber = res.pageNumber;
    page.pageSize = res.pageSize;
    page.totalPage = res.totalPage;
    page.totalRow = res.totalRow;
    page.records = res.records;
    pageLoading.value = false;
    return {...page};
  }

  /**
   * 初始化页面
   */
  async function initialPage(){
    return await loadPageData(page.pageNumber);
  }

  /**
   * 重置
   */
  async function resetPage() {
    page.pageNumber = initialPageNumber;
    page.pageSize = initialPageSize;
    page.totalPage = 0;
    page.totalRow = -1;
    page.records = [];
    return await loadPageData(page.pageNumber);
  }
  /**
   * 下一页
   */
  async function nextPage() {
    if (isLastPage.value) {
      throw new Error("已经是最后一页");
    } else {
      return await loadPageData(page.pageNumber+1);
    }
  }

  /**
   * 上一页
   */
  async function prevPage() {
    if (isFirstPage.value) {
      throw new Error("已经是第一页");
    } else {
      return await loadPageData(page.pageNumber -1 );
    }
  }

  /**
   * 跳到某页
   */
  async function goPage(num: number) {
    if (page.pageNumber < 1 || page.pageNumber > page.totalPage) {
      throw new Error("请输入有效的页码");
    } else if (page.pageNumber != num) {
      return await loadPageData(num);
    } else {
      return { ...page };
    }
  }
  return {
    page,
    resetPage,
    nextPage,
    prevPage,
    goPage,
    pageLoading,
    isFirstPage,
    isLastPage,
    initialPage
  };
}
